<template>
  <div class="pay-list employee_list">
    <div class="search-box">
      <Row type="flex"
           justify="space-between">
        <Row type="flex">
          <Col class="search-item">
          <span class="search-label">手机号码:</span>
          <Input v-model.trim="formValidate.phoneNumber"
                 :maxlength="11"
                 @on-keyup="allowNumber"
                 placeholder="手机号码" />
          </Col>
          <Col class="search-item">
          <span class="search-label">姓名:</span>
          <Input v-model.trim="formValidate.username"
                 :maxlength="20"
                 @on-keyup="filterSpace"
                 placeholder="姓名" />
          </Col>
          <Col class="search-item">
          <span class="search-label">角色:</span>
          <Select v-model="formValidate.roleIdList"
                  :max-tag-count="1"
                  :max-tag-placeholder="maxTagPlaceholder"
                  filterable
                  multiple
                  style="width:180px"
                  class="select-shop-item"
                  :class="{'select-shop-width': formValidate.roleIdList.length > 0}"
                  @on-change="roleIdList_change">
            <Option v-for="item in roleIdList"
                    :value="item.value"
                    :key="item.value">{{ item.label }}</Option>
          </Select>
          </Col>
          <Col class="search-item">
          <Button class="search-btn"
                  type="primary"
                  @click="query">查询</Button>
          </Col>
          <Col class="search-item">
          <Button class="search-btn"
                  @click="chongzhi">重置</Button>
          </Col>
        </Row>
        <Row type="flex"
             style="padding-right:16px">
          <Col>
          <div id="btn-export">
            <Row type="flex"
                 justify="end"
                 style="width:100%;padding-right:16px">
              <Col class="search-item">
              <Button class="search-btn"
                      @click="skipLead"
                      v-if="hasPermission('moms:staff:import')">导入</Button>
              </Col>
              <Col class="search-item">
              <Button class="search-btn"
                      :disabled='this.Tabledata.length>0 ? false: true'
                      v-if="hasPermission('moms:staff:export')"
                      @click='exportData'>导出</Button>
              </Col>
              <Col class="search-item">
              <Button class="search-btn"
                      type="primary"
                      @click="add"
                      v-if="hasPermission('moms:staff:create')">添加</Button>
              </Col>
            </Row>
          </div>
          </Col>
          <Col class="search-item">
          <Button v-if="exampleShow"
                  @click="exampleOpen">收起筛选
            <Icon type="ios-arrow-up" />
          </Button>
          <Button v-else
                  @click="exampleOpen">更多筛选
            <Icon type="ios-arrow-down" />
          </Button>
          </Col>
        </Row>
      </Row>
      <div class="search-example"
           v-show="exampleShow">
        <Row type="flex">
          <Col class="search-item">
          <span class="search-label">员工状态:</span>
          <Select v-model="formValidate.status"
                  placeholder="请选择"
                  @on-change="change_Select">
            <Option value=-1>全部</Option>
            <Option value=1>开启</Option>
            <Option value=0>关闭</Option>
          </Select>
          </Col>
          <Col class="treeselect_box"
               style="margin-left: 30px">
          <span class="search-label"
                style="margin-right: 8px">组织机构:</span>
          <treeselect class="list_treeselect"
                      style="width:180px;"
                      v-model='formValidate.orgId'
                      noResultsText="未搜索符合的组织机构"
                      noOptionsText="组织机构为空"
                      :options="options"
                      :normalizer="normalizer"
                      @select="selectList"
                      placeholder="请选择组织机构" />
          </Col>
        </Row>
      </div>
      <div id="btn-export-show">
        <Row type="flex"
             justify="end"
             style="width:100%;padding-right:16px">
          <Col class="search-item">
          <Button class="search-btn"
                  @click="skipLead"
                  v-if="hasPermission('moms:staff:import')">导入</Button>
          </Col>
          <Col class="search-item">
          <Button class="search-btn"
                  :disabled='this.Tabledata.length>0 ? false: true'
                  v-if="hasPermission('moms:staff:export')"
                  @click='exportData'>导出</Button>
          </Col>
          <Col class="search-item">
          <Button class="search-btn"
                  type="primary"
                  @click="add"
                  v-if="hasPermission('moms:staff:create')">添加</Button>
          </Col>
        </Row>
      </div>
    </div>
    <Table stripe
           :height="this.tableHeight"
           class="table-list"
           ref="selection"
           :columns="columns"
           :loading="loading"
           :data="Tabledata"
           @on-selection-change="table_check">
      <template slot-scope="{ row, index }"
                slot="status">
        <span>
          <i-switch v-model="row.status"
                    :disabled="!hasPermission('moms:staff:updatestatus')"
                    @on-change="switch_change(row,index)">
            <span slot="open">开</span>
            <span slot="close">关</span>
          </i-switch>
        </span>
      </template>
      <template slot-scope="{ row, index }"
                slot="action">
        <i class="iconsys icondetail"
           @click="det(row,index)"
           title="查看详情"
           v-if="hasPermission('moms:staff:detail')"></i>
        <i class="iconsys iconedit"
           @click="uptShow(row,index)"
           title="编辑"
           v-if="hasPermission('moms:staff:update')"></i>
        <Poptip confirm
                title="你确定要删除吗？"
                @on-ok="ok(row, index)"
                @on-cancel="cancel"
                class="poptip_del">
          <i class="iconsys icondel"
             title="删除"
             v-if="hasPermission('moms:staff:delete')"></i>
        </Poptip>
        <i class="iconsys iconshuju"
           @click="goDataSet(row)"
           title="数据权限"
           v-if="hasPermission('moms:staff:datapermission')"></i>
        <i class="iconsys icongongneng"
           @click="goFunctionSet(row)"
           title="功能权限"
           v-if="hasPermission('moms:staff:functionpermission')"></i>
        <Poptip confirm
                title="你确定要重置密码吗？"
                @on-ok="resetpassword(row, index)"
                @on-cancel="cancel"
                class="poptip_del">
          <i class="iconsys iconpassword2"
             title="重置密码"
             v-if="hasPermission('moms:staff:resetpassword')"></i>
        </Poptip>
      </template>
    </Table>
    <Row type="flex">
      <Col span="12"
           class="module-menu-nav">
      <Button class="module-menu-margin"
              @click="handleSelectAll"
              v-if="hasPermission(['moms:staff:updatestatus', 'moms:staff:delete'])">{{btnTitle}}</Button>
      <Dropdown placement="top"
                @on-click='batchAll'
                v-if="hasPermission(['moms:staff:updatestatus', 'moms:staff:delete'])">
        <Button class="check_all">批量操作</Button>
        <DropdownMenu slot="list"
                      style="text-align:center">
          <DropdownItem name='1'
                        v-if="hasPermission('moms:staff:updatestatus')">批量关闭</DropdownItem>
          <DropdownItem name='2'
                        v-if="hasPermission('moms:staff:updatestatus')">批量开启</DropdownItem>
          <DropdownItem name='3'
                        v-if="hasPermission('moms:staff:delete')">批量删除</DropdownItem>
        </DropdownMenu>
      </Dropdown>
      </Col>
      <Col span="12">
      <div class="page-box">
        <Page :total="total"
              :current='page.pageIndex'
              show-total
              show-sizer
              @on-change="pageNum"
              :page-size="page.pageSize"
              ref="pages"
              @on-page-size-change="selectSize" />
      </div>
      </Col>
    </Row>
  </div>
</template>
<script>
import { setSwitchDisable, setSwitchEnable, setUserDelete, getEmployeeQuery, getRoleList, getEmployeeTree, exportEmployee, resetPassword } from '@/api/system/employee.js'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { blobToXls } from '@/libs/blobToXls'
export default {
  name: 'employee_list',
  components: { Treeselect },
  data () {
    return {
      tableHeight: 0,
      btnTitle: '全选',
      isDelete: true,
      searchPhoneNumber: '',
      searchName: '',
      formValidate: {
        merchantId: this.$store.state.user.merchantId,
        orgId: null, // 组织机构
        roleIdList: [],
        status: '-1',
        username: '',
        phoneNumber: ''
      },
      exampleShow: false,
      loading: true,
      allStatus: true, // 全选状态
      roleIdList: [
      ],
      options: [],
      normalizer (node) {
        if (node.childList) {
          if (node.childList.length > 0) {
            return {
              id: node.id,
              label: node.orgName,
              children: node.childList
            }
          } else {
            return {
              id: node.id,
              label: node.orgName
            }
          }
        }
      },
      total: null,
      page: {
        pageIndex: 1,
        pageSize: 10
      },
      ckeckList: [],
      columns: [
        {
          type: 'selection',
          width: 60
        },
        {
          title: '手机号码',
          key: 'phoneNumber',
          width: 150
        },
        {
          title: '姓名',
          key: 'username'
        },
        {
          title: '角色',
          key: 'newName'
        },
        {
          title: '组织机构',
          key: 'orgName'
        },
        {
          title: '状态',
          slot: 'status',
          width: 110
        },
        {
          title: '操作时间',
          key: 'updateTime'
        }
      ],
      Tabledata: [
      ]
    }
  },
  watch: {
    '$route' (newRoute) {
      if (newRoute.name === 'employee_list') {
        // this.getList(this.formValidate, { pageIndex: 0 })
        // this.$refs.pages.currentPage = 1
        this.getList(this.formValidate, { pageIndex: this.$refs.pages.currentPage })
      }
    },
    'formValidate.orgId': function (newVal) {
      if (!newVal) {
        this.formValidate.orgId = null
        this.loading = true
        this.getList(this.formValidate, { pageIndex: 0 })
        this.$refs.pages.currentPage = 1
      }
    },
    ckeckList (data) {
      if (data.length === this.Tabledata.length && this.Tabledata.length !== 0) {
        this.btnTitle = '取消全选'
        this.allStatus = false
      } else {
        this.btnTitle = '全选'
        this.allStatus = true
      }
    }
  },
  created () {
    if (this.hasPermission(['moms:staff:detail', 'moms:staff:update', 'moms:staff:delete', 'moms:staff:datapermission', 'moms:staff:functionpermission', 'moms:staff:resetpassword'])) {
      this.columns.push({
        title: '操作',
        width: 300,
        slot: 'action'
      })
    }
  },
  mounted () {
    this.getList()
    this.getRoleAll()
    this.getOrgTree()
  },
  methods: {
    maxTagPlaceholder (num) {
      return '...'
    },
    // 导出
    exportData () {
      exportEmployee({
        fileName: 'employee',
        type: 'EXCEL'
      }).then(res => {
        if (res.status === 200) {
          blobToXls(res.data, '导出员工列表')
        }
      })
    },
    filterSpace (e) {
      e.target.value = e.target.value.replace(/\s+/g, '')
      this.formValidate.username = e.target.value
    },
    allowNumber (e) {
      e.target.value = e.target.value.replace(/\s+/g, '')
      this.formValidate.phoneNumber = e.target.value.replace(/[^0-9]+/g, '')
    },
    // 筛选按钮
    exampleOpen () {
      this.exampleShow = !this.exampleShow
    },
    selectList (data) { // 选择组织机构树
      this.formValidate.orgId = data.id
      this.loading = true
      this.getList(this.formValidate, { pageIndex: 0 })
      this.$refs.pages.currentPage = 1
    },
    getOrgTree () { // 获取组织机构树
      getEmployeeTree({
        'merchantId': this.$store.state.user.merchantId,
        'status': 1
        // 'orgType': 0
      }).then((res) => {
        if (res.data.status === 200) {
          this.options.push(res.data.data)
        } else {
          this.$Message.error(res.data.error)
        }
      })
    },
    // 导入
    skipLead () {
      this.$router.push({ name: 'employee_import' })
    },
    goFunctionSet (row) {
      this.$router.push({
        name: 'employee_function_permission',
        params: {
          id: row.id
        },
        query: {
          orgId: row.orgId
        }
      })
    },
    chongzhi () {
      this.searchPhoneNumber = ''
      this.searchName = ''
      this.formValidate.username = ''
      this.formValidate.phoneNumber = ''
      this.formValidate.roleIdList = []
      this.formValidate.status = '-1'
      this.formValidate.orgId = null
      this.getList(this.formValidate, { pageIndex: 0 })
      this.$refs.pages.currentPage = 1
    },
    batchAll (val) { // 批量
      if (this.ckeckList.length > 0) {
        let flag = true
        let arr = []
        let orgIdArr = []
        this.ckeckList.forEach(item => {
          arr.push(item.id)
          orgIdArr.push(item.orgId)
          if (item.status) {
            flag = false
          }
          // let param = { 'merchantId': this.$store.state.user.merchantId, idList: arr, orgId: orgIdArr.join(',') }
          let param = { load: { 'merchantId': this.$store.state.user.merchantId, idList: arr, orgId: orgIdArr.join(',') }, valite: {} }
          this.$Modal.confirm({
            title: val === '1' ? '确认批量关闭吗？' : val === '2' ? '确认批量开启吗？' : '确认批量删除吗？',
            onOk: () => {
              if (val === '1') {
                this.closeSwitch(param)
              } else if (val === '2') {
                this.openSwitch(param)
              } else {
                if (flag) {
                  setUserDelete(param.load).then((res) => {
                    if (res.data.status === 200) {
                      this.$Message.success('删除成功')
                      this.getList(this.formValidate, { pageIndex: this.$refs.pages.currentPage })
                      this.ckeckList = []
                    } else {
                      this.$Message.error(`${res.data.error}`)
                    }
                  })
                } else {
                  this.$Message.error('状态启用时不可删除')
                }
              }
            },
            onCancel: () => { }
          })
        })
      } else {
        this.$Message.error('请至少选择一项')
      }
    },
    table_check (data) {
      this.ckeckList = data.map(item => {
        return { id: item.id, status: item.status, orgId: item.orgId }
      })
    },
    change_Select (value) {
      this.loading = true
      this.getList(this.formValidate, { pageIndex: 0 })
      this.$refs.pages.currentPage = 1
    },
    password (data) {
      this.$router.push({
        name: 'employee_modify_password',
        params: {
          id: data.id
        },
        query: {
          orgId: data.orgId
        }
      })
    },
    handleSelectAll () {
      this.$refs.selection.selectAll(this.allStatus)
    },
    query () {
      this.loading = true
      this.searchPhoneNumber = this.formValidate.phoneNumber
      this.searchName = this.formValidate.username
      this.getList(this.formValidate, { pageIndex: 0 })
      this.$refs.pages.currentPage = 1
    },
    getRoleAll () { // 获取角色
      getRoleList({
        'merchantId': this.$store.state.user.merchantId,
        'status': 1
      }).then((res) => {
        if (res.data.status === 200) {
          res.data.data.forEach(ele => {
            this.$set(ele, 'label', ele.roleName)
            this.$set(ele, 'value', ele.id)
          })
          this.roleIdList = res.data.data
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    roleIdList_change (arr) { // 选择角色 获取roleIdList
      this.formValidate.roleIdList = arr
      this.loading = true
      this.getList(this.formValidate, { pageIndex: 0 })
    },
    selectSize (size) {
      this.loading = true
      this.page.pageSize = size
      this.getList({ pageIndex: this.$refs.pages.currentPage - 1 }, this.formValidate)
    },
    pageNum (page) {
      this.loading = true
      this.getList({ pageIndex: page }, this.formValidate)
    },
    getList (res, res1) {
      this.tableHeight = 0
      getEmployeeQuery({
        ...this.page,
        ...res,
        ...res1,
        username: this.searchName,
        phoneNumber: this.searchPhoneNumber,
        status: this.formValidate.status === '-1' ? '' : this.formValidate.status,
        'merchantId': this.$store.state.user.merchantId
      }).then((res) => {
        // this.loading = true
        if (res.data.status === 200) {
          this.loading = false
          this.ckeckList = []
          this.total = res.data.data.total
          res.data.data.records.forEach(ele => {
            if (ele.status === 1) {
              this.$set(ele, 'status', true)
            } else {
              this.$set(ele, 'status', false)
            }
            ele.newName = ''
            if (ele.roleList) {
              ele.roleList.forEach(it => {
                ele.newName = ele.newName + it.roleName + '|'
              })
              ele.newName = ele.newName.substring(0, ele.newName.length - 1)
            }
          })
          this.Tabledata = res.data.data.records
          if (res.data.data.records && res.data.data.records.length >= 10) {
            this.tableHeight = 520
          }
        } else {
          this.loading = false
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    uptShow (row, index) { // 编辑
      this.$router.push({
        name: 'employee_edit',
        params: {
          id: row.id
        },
        query: {
          orgId: row.orgId
        }
      })
      // getUserInfos({
      //   orgId: row.orgId,
      //   id: row.id
      // }).then(res => {
      //   if (res.status === 200) {
      //     if (res.data.data === null) {
      //       this.$Message.error(res.data.message)
      //     } else {
      //       this.$router.push({
      //         name: 'employee_edit',
      //         params: {
      //           id: row.id,
      //           orgId: row.orgId
      //         }
      //       })
      //     }
      //   }
      // })
    },
    det (row, index) { // 详情
      this.$router.push({
        name: 'employee_detail',
        params: {
          id: row.id
        },
        query: {
          orgId: row.orgId
        }
      })
      // getUserInfos({
      //   orgId: row.orgId,
      //   id: row.id
      // }).then(res => {
      //   if (res.status === 200) {
      //     if (res.data.data === null) {
      //       this.$Message.error(res.data.message)
      //     } else {
      //       this.$router.push({
      //         name: 'employee_detail',
      //         params: {
      //           id: row.id
      //         },
      //         query: {
      //           orgId: row.orgId
      //         }
      //       })
      //     }
      //   }
      // })
    },
    ok (row, index) {
      if (this.isDelete) {
        if (!this.isDelete) {
          return
        }
        this.isDelete = false
        if (!row.status) {
          setTimeout(() => {
            setUserDelete({
              'merchantId': this.$store.state.user.merchantId,
              'id': row.id,
              'orgId': row.orgId
            }).then((res) => {
              this.isDelete = true
              if (res.data.status === 200) {
                this.$Message.success('删除成功')
                this.getList(this.formValidate, { pageIndex: this.$refs.pages.currentPage })
              } else {
                this.$Message.error(`${res.data.error}`)
              }
            })
          }, 200)
        } else {
          this.$Message.error('启用状态无法删除')
          setTimeout(() => {
            this.isDelete = true
          }, 400)
        }
      }
    },
    resetpassword (row, index) {
      resetPassword({
        phoneNumber: row.phoneNumber,
        id: row.id
      }).then(res => {
        this.isDelete = true
        if (res.data.status === 200) {
          this.$Message.success('密码重置成功')
          this.getList(this.formValidate, { pageIndex: this.$refs.pages.currentPage })
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    cancel () {
    },
    // 开启
    openSwitch (param) {
      setSwitchEnable(param.load).then((res) => {
        if (res.status === 200) {
          if (res.data.status === 200) {
            if (param.load.idList) {
              this.Tabledata.forEach((ele, idx) => {
                this.ckeckList.forEach(item => {
                  if (ele.id === item.id) {
                    this.$set(this.Tabledata[idx], 'status', true)
                    item.status = !item.status
                  }
                })
              })
              this.$Message.success('批量开启成功！')
              // this.getList(this.formValidate, { pageIndex: this.$refs.pages.currentPage })
              this.ckeckList = []
            } else {
              this.$set(this.Tabledata[param.valite.index], 'status', true)
              this.$Message.success('开启成功！')
            }
          } else {
            if (param.load.idList) {
            } else {
              this.$nextTick(() => {
                this.$set(this.Tabledata[param.valite.index], 'status', !param.valite.status)
              })
            }
            this.$Message.error(`${res.data.error}`)
          }
        }
      })
    },
    // 关闭
    closeSwitch (param) {
      setSwitchDisable(param.load).then((res) => {
        if (res.status === 200) {
          if (res.data.status === 200) {
            if (param.load.idList) {
              this.Tabledata.forEach((ele, idx) => {
                this.ckeckList.forEach(item => {
                  if (ele.id === item.id) {
                    this.$set(this.Tabledata[idx], 'status', false)
                    item.status = !item.status
                  }
                })
              })
              this.$Message.success('批量关闭成功！')
              // this.getList(this.formValidate, { pageIndex: this.$refs.pages.currentPage })
              this.ckeckList = []
            } else {
              this.$set(this.Tabledata[param.valite.index], 'status', false)
              this.$Message.success('关闭成功！')
            }
          } else {
            if (param.load.idList) {
            } else {
              this.$nextTick(() => {
                this.$set(this.Tabledata[param.valite.index], 'status', !param.valite.status)
              })
            }
            this.$Message.error(`${res.data.error}`)
          }
        }
      })
    },
    switch_change (row, index) { // 开关
      // let param = { 'merchantId': this.$store.state.user.merchantId, id: row.id, orgId: row.orgId }
      let param = { load: { 'merchantId': this.$store.state.user.merchantId, id: row.id, orgId: row.orgId }, valite: { status: row.status, index: index } }
      this.$set(this.Tabledata[index], 'status', row.status)
      if (row.status) {
        this.openSwitch(param)
      } else {
        this.closeSwitch(param)
      }
    },
    lead () {
      this.$router.push({
        name: 'employee_import'
      })
    },
    add () {
      this.$router.push({
        name: 'employee_create'
      })
    },
    goDataSet (row) {
      this.$router.push({
        name: 'employee_data_permission',
        params: {
          id: row.id
        },
        query: {
          orgId: row.orgId
        }
      })
      // getResourceList({
      //   'merchantId': this.$store.state.user.merchantId,
      //   'resType': 0
      // }).then(res => {
      //   if (res.status === 200) {
      //     let appId = res.data.data[0].id
      //     getUserData({
      //       'orgId': row.orgId,
      //       'merchantId': this.$store.state.user.merchantId,
      //       'id': row.id,
      //       'roleId': row.roleList[0].id,
      //       'appId': appId
      //     }).then(res => {
      //       if (res.status === 200) {
      //         if (res.data.data.childList.length > 0) {
      //           this.$router.push({
      //             name: 'employee_data_permission',
      //             params: {
      //               id: row.id
      //             }
      //           })
      //         } else {
      //           this.$Message.error('您没有此操作权限')
      //         }
      //       }
      //     })
      //   }
      // })
    }
  }
}
</script>
<style lang="less" scoped>
.employee_list {
  .search-btn {
    width: 80px;
  }
}
</style>
<style lang="less">
.employee_list {
  .select-shop-item {
    height: 35px;
    .ivu-select-selection {
      height: 35px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
    .ivu-tag {
      max-width: 100px;
    }
  }
  .select-shop-item .ivu-select-dropdown {
    width: 300px;
  }
  .select-shop-item .ivu-select-item {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  .treeselect_box {
    display: flex;
    align-items: center;
    margin-left: 30px;
    padding-top: 24px;
    span {
      line-height: 30px;
      margin-right: 8px;
    }
  }
}
.poptip_del .ivu-poptip-body .ivu-icon {
  left: 18px;
}
.vue-treeselect__control,
.vue-treeselect__input-container {
  height: 32px !important;
}
</style>
<style>
.employee_list .select-shop-width .ivu-select-input {
  width: 40px !important;
}
</style>
